<template>
    <div class="app">
        <div class="title">
            <div class="icon" @click="hanldeBack">
                <el-icon><ArrowLeftBold /></el-icon>
            </div>
            <div class="title-left">补版</div>
            <div class="title-right" @click="handleList">补版记录</div>
        </div>
        <div style="margin-top: 20px">
            <el-form
                :model="form"
                :rules="rules"
                :disabled="flag"
                ref="userRef"
                label-width="100px"
            >
                <el-row :gutter="20">
                    <el-form-item label="补版日期" prop="replenishDate">
                        <el-date-picker
                            style="width: 200px"
                            clearable
                            v-model="form.replenishDate"
                            value-format="YYYY-MM-DD"
                            type="date"
                            placeholder="请选择日期"
                        />
                    </el-form-item>
                </el-row>
                <el-row :gutter="20">
                    <el-form-item label="申请人" prop="applyName">
                        <el-input
                            style="width: 200px"
                            v-model="form.applyName"
                            placeholder="请输入申请人"
                        />
                    </el-form-item>
                </el-row>
                <!-- <el-row :gutter="20">
                        <el-form-item label="申请机台/部门" prop="applyMachine">
                            <el-select
                                v-model="form.applyMachine"
                                clearable
                                filterable
                                style="width: 100%"
                            >
                                <el-option
                                    v-for="item in Myoptions"
                                    :key="item.pid"
                                    :label="item.machineName"
                                    :value="item.pid"
                                />
                            </el-select>
                        </el-form-item>
                </el-row> -->
                <el-row :gutter="20">
                    <el-form-item label="申请日期" prop="applyDate">
                        <el-date-picker
                            style="width: 200px"
                            readonly
                            v-model="form.applyDate"
                            value-format="YYYY-MM-DD"
                            type="date"
                            placeholder="请选择时间"
                        />
                    </el-form-item>
                </el-row>

                <el-row :gutter="20">
                    <el-form-item label="备注">
                        <el-input
                            style="width: 200px"
                            v-model="form.remark"
                            type="textarea"
                            placeholder="请输入内容"
                        ></el-input>
                    </el-form-item>
                </el-row>
            </el-form>
        </div>

        <el-collapse v-model="activeNames">
            <el-collapse-item disabled title="补版明细" name="2">
                <template #title>
                    <el-icon style="color: #4479f6">
                        <Position />
                    </el-icon>
                    <span class="title">补版明细</span>
                </template>
                <el-button
                    v-if="!flag"
                    style="margin-bottom: 10px"
                    type="primary"
                    size="small"
                    @click="handleAddStorage"
                >
                    选择生产单
                </el-button>
                <el-table v-loading="loading" class="table-form" :data="mesReplenishDetailList">
                    <el-table-column
                        label="序号"
                        width="60"
                        type="index"
                        align="center"
                    ></el-table-column>
                    <el-table-column
                        label="制版序列号"
                        min-width="120"
                        prop="printProduceNo"
                        align="center"
                    ></el-table-column>
                    <el-table-column
                        label="生产单编码"
                        align="center"
                        width="120"
                        prop="produceNo"
                    ></el-table-column>

                    <el-table-column
                        label="印刷序列号"
                        min-width="120"
                        prop="printProduceNo"
                        align="center"
                    ></el-table-column>
                    <el-table-column label="品种" prop="breed" min-width="160" align="center">
                        <!-- <template #default="scope">
                              <dict-tag
                                  :options="ems_order_breed_type"
                                  :value="scope.row.breed"
                              />
                          </template> -->
                    </el-table-column>
                    <el-table-column
                        label="组成"
                        min-width="160"
                        prop="composition"
                        align="center"
                    ></el-table-column>
                    <el-table-column
                        label="印张"
                        width="120"
                        prop="sheet"
                        align="center"
                    ></el-table-column>
                    <el-table-column
                        label="印数"
                        width="120"
                        prop="printAmount"
                        align="center"
                    ></el-table-column>
                    <el-table-column label="印色" width="120" prop="printColour" align="center">
                        <template #default="scope">
                            <dict-tag
                                :options="ems_order_print_color"
                                :value="scope.row.printColour"
                            />
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="版材数量"
                        width="120"
                        prop="sheetAmount"
                        align="center"
                    ></el-table-column>
                    <el-table-column label="版材尺寸" prop="sheetSize" width="120" align="center">
                        <template #default="scope">
                            <dict-tag
                                :options="ems_machine_info_size"
                                :value="scope.row.sheetSize"
                            />
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="制版数量"
                        width="120"
                        align="center"
                        prop="replenishNumber"
                    >
                        <template #default="scope">
                            <el-form-item>
                                <el-input
                                    v-model="scope.row.replenishNumber"
                                    placeholder="请输入"
                                ></el-input>
                            </el-form-item>
                        </template>
                    </el-table-column>
                    <el-table-column label="烤版" width="120" prop="kaoban" align="center">
                        <template #default="scope">
                            {{ scope.row?.kaoban == 1 ? '是' : scope.row?.kaoban == 2 ? '否' : '' }}
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="备注"
                        width="120"
                        align="center"
                        prop="remark"
                        :show-overflow-tooltip="true"
                    >
                        <template #default="scope">
                            <span v-if="flag">{{ scope.row.remark }}</span>
                            <el-form-item v-else>
                                <el-input
                                    v-model="scope.row.remark"
                                    placeholder="请输入"
                                ></el-input>
                            </el-form-item>
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="操作"
                        v-if="!flag"
                        align="center"
                        fixed="right"
                        class-name="small-padding fixed-width"
                    >
                        <template #default="scope">
                            <el-tooltip content="删除" placement="top">
                                <el-button
                                    link
                                    type="primary"
                                    icon="Delete"
                                    @click="handleDelete(scope.row)"
                                ></el-button>
                            </el-tooltip>
                        </template>
                    </el-table-column>
                </el-table>
            </el-collapse-item>
        </el-collapse>
        <!-- 领用库单明细 -->
        <orderList
            :visible="orderListOpen"
            @changeUpdate="changeOrderData"
            :orderSelectList="orderSelectList"
            :machineId="selectMachineId"
            @cancel="
                () => {
                    orderListOpen = false
                }
            "
        ></orderList>
        <SearchWorkBench
            :visible="searchVisible"
            @changeUpdate="changeWorkBenchData"
            @cancel="
                () => {
                    searchVisible = false
                }
            "
        ></SearchWorkBench>
        <el-button v-if="!flag" class="footer" @click="submitForm">提交</el-button>
    </div>
</template>

<script setup>
import { getList as getDataList } from '@/api/basicInfo/workbench'
import SearchWorkBench from '@/components/SearchWorkBench'
import orderList from './orderList.vue'
import {
    editMesreplenish,
    addMesreplenish,
    getByIdMesreplenish,
} from '@/api/production/supplementary.js'
import useTagsViewStore from '@/store/modules/tagsView'
import useUserStore from '@/store/modules/user'
import { ElMessage } from 'element-plus'
import { nextTick } from 'vue'
const userStore = useUserStore()
const tagsViewStore = useTagsViewStore()
const { proxy } = getCurrentInstance()
const {
    ems_machine_info_size,
    ems_order_make_up,
    ems_order_print_color,
    ems_order_breed_type,
    ems_order_make_up_fm,
} = proxy.useDict(
    'ems_order_breed_type',
    'ems_machine_info_size',
    'ems_order_make_up',
    'ems_order_print_color',
    'ems_order_make_up_fm'
)

const route = useRoute()
const router = useRouter()
const orderListOpen = ref(false)
const orderSelectList = ref([])
const activeNames = ['1', '2']
const userRef = ref(null)
const selectMachineId = ref('')
const flag = ref(false)
const searchVisible = ref(false)
const Myoptions = ref([
    { machineName: '旧版房', pid: '999999' },
    { machineName: '印刷机', pid: '888888' },
])
const loading = ref(false)
const userInfo = useUserStore()
const data = reactive({
    form: {},
    mesReplenishDetailList: [],
    rules: {
        applyName: [{ required: true, message: '申请人不能为空', trigger: 'blur' }],
        replenishDate: [
            { required: true, message: '补版日期不能为空', trigger: ['blur', 'change'] },
        ],
        // applyMachine: [
        //     { required: true, message: '申请机台/部门不能为空', trigger: ['blur', 'change'] },
        // ],
    },
})

const { form, rules, mesReplenishDetailList } = toRefs(data)

nextTick(() => {
    form.value.createBy = userInfo.name
    // form.value.applyName = userInfo.name
    form.value.machineId = userStore.workbranchId
    selectMachineId.value = userStore.workbranchId
})
const hanldeBack = () => {
    router.push('todo')
}
const handleList = () => {
    router.push({
        path: '/supplementaryList',
    })
}
if (route.query.id) {
    getByIdMesreplenish(route.query.id).then(res => {
        Object.assign(form.value, { ...res.data })
        mesReplenishDetailList.value = res.data.mesReplenishDetailList
        if (route.query.info) {
            flag.value = true
        }
    })
} else {
    flag.value = false
    form.value = {}
    mesReplenishDetailList.value = []
}
// 打开机台页面
const openDialog = () => {
    searchVisible.value = true
}
// 选中的机台
const changeWorkBenchData = row => {
    form.value.applyMachine = row.applyMachine
    form.value.machineId = row.pid
    selectMachineId.value = row.pid
    searchVisible.value = false
}

const getChoiceList = async () => {
    const res = await getDataList({ pageNum: 1, pageSize: 100 })
    Myoptions.value = [{ machineName: '旧版房', pid: '999999' }, ...res.rows]
}

// getChoiceList()
// 获取当前时间
const getCurrentDateTime = () => {
    const now = new Date()
    const year = now.getFullYear()
    const month = String(now.getMonth() + 1).padStart(2, '0')
    const day = String(now.getDate()).padStart(2, '0')
    const hours = String(now.getHours()).padStart(2, '0')
    const minutes = String(now.getMinutes()).padStart(2, '0')
    const seconds = String(now.getSeconds()).padStart(2, '0')
    form.value.applyDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}
getCurrentDateTime()

// 新增入库明细
const handleAddStorage = () => {
    orderSelectList.value = mesReplenishDetailList.value
    orderListOpen.value = true
}
// 选中的入库明细
const changeOrderData = row => {
    const codeSet = new Set(mesReplenishDetailList.value.map(data => data.producePrintId))
    row.forEach(item => {
        if (!codeSet.has(item.producePrintId)) {
            mesReplenishDetailList.value.push({ ...item })
            codeSet.add(item.producePrintId)
        }
    })
    orderListOpen.value = false
}

// 删除
const handleDelete = row => {
    proxy.$modal.confirm('是否确认删除该数据？').then(function () {
        mesReplenishDetailList.value = mesReplenishDetailList.value.filter(item =>
            item.producePrintId ? item.producePrintId != row.producePrintId : item.id != row.id
        )
        proxy.$modal.msgSuccess('删除成功')
    })
}
// 确认
const submitForm = () => {
    userRef.value.validate(valid => {
        if (valid) {
            if (route.query.id) {
                editMesreplenish({
                    ...form.value,
                    mesReplenishDetailList: mesReplenishDetailList.value,
                }).then(res => {
                    ElMessage({
                        message: '编辑成功',
                        type: 'success',
                    })
                    goBack()
                })
            } else {
                addMesreplenish({
                    ...form.value,
                    status: 1,
                    mesReplenishDetailList: mesReplenishDetailList.value,
                }).then(res => {
                    ElMessage({
                        message: '新增成功',
                        type: 'success',
                    })
                    goBack()
                })
            }
        }
    })
}
//  返回
const goBack = () => {
    tagsViewStore.delView(route)
    router.go(-1)
}
</script>

<style lang="scss" scoped>
.app {
    padding: 20px;
}

.footer {
    background-color: #eb722f;
    color: #fff;
    display: flex;
    justify-content: center;
    align-items: center;
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    height: 42px;
    line-height: 42px;
    z-index: 9999;
}

.title {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 50px;
    line-height: 50px;
    box-sizing: border-box;
    font-weight: 700;
    font-size: 16px;
    .icon {
        width: 30px;
        height: 56px;
        border: 3px solid #eb722f;
        border-right: 0px;
        border-radius: 5px 0 0 5px;
        background-color: #fcf2e7;
        color: #eb722f;
        display: flex;
        justify-content: center;
        align-items: center;
    }
    .title-left {
        flex: 1;
        border: 3px solid #eb722f;
        // border-radius: 5px 0 0 5px;
        border-left: 0px;
        background-color: #fcf2e7;
        color: #eb722f;
        display: flex;
        justify-content: center;
        align-items: center;
    }

    .title-right {
        height: 56px;
        width: 100px;
        background-color: #eb722f;
        border-radius: 0 5px 5px 0;
        display: flex;
        justify-content: center;
        align-items: center;
        color: #fff;
    }
}
</style>
